package com.draw.core;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Drawing")
public class Drawing {
	private static final int LETTERSPATTERNSIZE = 12;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private int id;

	@ManyToOne
	@JoinColumn(name = "source", nullable = false)
	private User source;

	@ManyToOne
	@JoinColumn(name = "destination", nullable = false)
	private User destination;

	@ManyToOne
	@JoinColumn(name = "word", nullable = false)
	private Word word;

	@Column(name = "letters", nullable = false)
	private String letters;

	@OneToMany(mappedBy = "drawing")
	private Set<Line> lines;

	@Column(name = "successfull")
	private boolean successfull;

	@Column(name = "done", nullable = false)
	private boolean done = false;

	public int getId() {
		return id;
	}

	public User getSource() {
		return source;
	}

	public User getDestination() {
		return destination;
	}

	public Word getWord() {
		return word;
	}

	public String getLetters() {
		return letters;
	}

	public void generateLetters() {
		Random rand = new Random();
		String pattern = this.word.getWord();
		while (pattern.length() < LETTERSPATTERNSIZE) {
			char l = (char) ('a' + rand.nextInt('z' - 'a'));
			pattern += l + "";
		}
		this.letters = pattern.toUpperCase();
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setSource(User source) {
		this.source = source;
	}

	public void setDestination(User destination) {
		this.destination = destination;
	}

	public void setWord(Word word) {
		this.word = word;
	}

	public void setLetters(String letters) {
		this.letters = letters;
	}

	public void addLine(Line line) {
		if (this.lines == null) {
			this.lines = new HashSet<Line>();
		}
		this.lines.add(line);
		line.setDrawing(this);
	}

	public Set<Line> getLines() {
		return lines;
	}

	public void setLines(Set<Line> lines) {
		if (lines == null) {
			this.lines = null;
		} else {
			this.lines = new TreeSet<Line>(lines);
		}
	}

	public boolean isSuccessfull() {
		return successfull;
	}

	public void setSuccessfull(boolean successfull) {
		this.successfull = successfull;
	}

	public boolean isDone() {
		return done;
	}

	public void setDone(boolean done) {
		this.done = done;
	}

	public void unpopulate() {
		for (Line l : lines) {
			l.setDrawing(null);
			l.unpopulate();
		}
	}

	public void populate() {
		for (Line l : lines) {
			l.setDrawing(this);
			l.populate();
		}
	}
}
